from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import JsonResponse

from rest_framework import status

from rest_framework.views import APIView

from ship_segments.models import ShipSegment
from ship_segments.serializers import ShipSegmentSerializer, ShipSegmentImportSerializer


class AddSegmentView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = ShipSegmentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"data": serializer.data, "code": 200})
        else:
            return JsonResponse({"message": serializer.errors, "code": 400})


class SegmentListView(APIView):
    def get(self, request, format=None):
        # 获取查询参数
        ship_type = request.query_params.get('ship_type', '')
        station_cycle = request.query_params.get('station_cycle', '')
        page = request.query_params.get('current', 1)
        page_size = request.query_params.get('pageSize', 10)

        # 构造查询条件
        queryset = ShipSegment.objects.all()

        if ship_type:
            queryset = queryset.filter(ship_type__icontains=ship_type)
        if station_cycle:
            queryset = queryset.filter(station_cycle=station_cycle)

        # 分页处理
        paginator = Paginator(queryset, page_size)
        try:
            segments = paginator.page(page)
        except PageNotAnInteger:
            segments = paginator.page(1)
        except EmptyPage:
            segments = paginator.page(paginator.num_pages)

        serializer = ShipSegmentSerializer(segments, many=True)

        return JsonResponse({
            "code": 200,
            "data": {
                "list": serializer.data,
                "total": paginator.count,
                "current": segments.number,
                "pageSize": page_size
            }
        }, status=status.HTTP_200_OK)


class ShipSegmentDetail(APIView):
    """
    根据 ship_segments_id 获取、更新或删除一个 ShipSegment 实例。
    """

    def get_object(self, pk):
        try:
            return ShipSegment.objects.get(ship_segments_id=pk)
        except ShipSegment.DoesNotExist:
            return None

    def get(self, request, pk, format=None):
        segment = self.get_object(pk)
        if not segment:
            return JsonResponse({"code": 404, "message": "未找到对应记录"}, status=status.HTTP_404_NOT_FOUND)
        serializer = ShipSegmentSerializer(segment)
        return JsonResponse({"code": 200, "data": serializer.data}, status=status.HTTP_200_OK)

    def put(self, request, pk, format=None):
        segment = self.get_object(pk)
        if not segment:
            return JsonResponse({"code": 404, "message": "未找到对应记录"}, status=status.HTTP_404_NOT_FOUND)

        serializer = ShipSegmentSerializer(segment, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"code": 200, "message": "修改成功", "data": serializer.data}, status=status.HTTP_200_OK)
        return JsonResponse({"code": 400, "message": "数据校验失败", "errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        segment = self.get_object(pk)
        if not segment:
            return JsonResponse({"code": 404, "message": "未找到对应记录"}, status=status.HTTP_404_NOT_FOUND)

        segment.delete()
        return JsonResponse({"code": 200, "message": "删除成功"}, status=status.HTTP_200_OK)


class BatchDeleteSegments(APIView):
    def post(self, request, *args, **kwargs):
        entities = request.data.get('entities', [])

        if not isinstance(entities, list) or len(entities) == 0:
            return JsonResponse(
                {"code": 400, "message": "请传入有效的实体列表"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 提取所有 ship_segments_id
        ids_to_delete = [entity.get('ship_segments_id') for entity in entities if 'ship_segments_id' in entity]

        if not ids_to_delete:
            return JsonResponse(
                {"code": 400, "message": "实体列表中没有有效的 ship_segments_id"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 删除符合条件的记录
        deleted_count, _ = ShipSegment.objects.filter(ship_segments_id__in=ids_to_delete).delete()

        return JsonResponse(
            {"code": 200, "message": f"成功删除 {deleted_count} 条记录"},
            status=status.HTTP_200_OK
        )


class BatchImportSegmentsView(APIView):
    def post(self, request, *args, **kwargs):
        data_list = request.data.get('list', [])

        if not isinstance(data_list, list) or len(data_list) == 0:
            return JsonResponse({
                "code": 400,
                "message": "请传入有效的对象数组"
            }, status=400)

        # 使用 ShipSegmentImportSerializer 校验数据
        serializer = ShipSegmentImportSerializer(data=data_list, many=True)

        if serializer.is_valid():
            # 构造模型实例并批量插入
            ShipSegment.objects.bulk_create([
                ShipSegment(**item) for item in serializer.validated_data
            ])

            return JsonResponse({
                "code": 200,
                "message": f"成功导入 {len(serializer.validated_data)} 条分段尺寸信息"
            }, status=201)
        else:
            return JsonResponse({
                "code": 400,
                "message": "部分数据校验失败",
                "errors": serializer.errors
            }, status=400)
